# this should be named site.py


import machine, sys, gc, builtins

# turn off damn pins on nodemcu
if sys.platform=='esp32':
    for Pin in (0, 2, 4, 5):
        machine.Pin(Pin, mode=machine.Pin.OUT, value=0)
else:
    #esp32cam
    for Pin in (0, 2, 4, 12, 13, 14, 16 ):
        machine.Pin(Pin, mode=machine.Pin.OUT, value=0)

del Pin

import uos as os

if "osdebug" in os.listdir("/"):
    # file transfer mode
    __import__("esp").osdebug(None)
    gc.collect()
    with open("free", "wb") as free:
        print(gc.mem_free(), file=free)
else:
    builtins.__UPY__ = True
    #builtins.__ANDROID__ = False
    #builtins.__WASM__ = False

    def report(free):
        global last
        gc.collect()
        mf = gc.mem_free()
        print("free", mf, "on", free, "=", mf - free, "delta", mf - last)
        try:
            return last - mf
        finally:
            last = mf

    try:
        with open("free") as f:
            free = int(f.read())
    except:
        free = 37280

    last = free

    free -= 192 + 32 + 16

    # if b'minitel' in [bytes(str,'utf-8') for str in os.listdir('/')]: #> qstr still cached why ... ?
    if "UART" in os.listdir("/"):
        os.dupterm(None, 1)
        UART = machine.UART(0, 1200)
        UART.init(1200, bits=7, parity=0, stop=1)

        sys.stdout = UART
        sys.stderr = UART
        sys.stdin = UART

        import webrepl

        webrepl.start()

    import utime as Time

    class config:  # COST ~ 192

        # FIXME: use gh by default
        srv = "http://192.168.1.66/mpy/%s/" % sys.platform
        free = free
        BPS = 115200
        GPIO = {}
        aio = False
        cache = False

        IP = "0.0.0.0"

        import network

        essid = b"micropython"
        password = b""

        AP_IF = network.WLAN(network.AP_IF)

        STA_IF = network.STA_IF
        STA_IF = network.WLAN(network.STA_IF)


        def connect(f):
            try:
                with open(f, "rb") as f:
                    essid = f.readline().decode().strip()
                    if not essid:
                        raise OSError(2)
                    return essid, f.readline().decode().strip()
            except:
                print("network", "config", "error")
                return b"ap", b""

        def isconnected(STA_IF, tmout=10):
            # required for weemos knock-off to process dhcp request
            while tmout and not STA_IF.isconnected():
                Time.sleep(1)
                print("", end=".")
                if tmout > 0:
                    tmout -= 1
            Time.sleep(.5)
            return STA_IF.ifconfig()[0]


        if "ap" in os.listdir("/"):
            essid, password = connect("ap")
            AP_IF.config(essid=essid, authmode=0, password=password, channel=9)
            AP_IF.active(True)
        AIP = AP_IF.ifconfig()[0]

        #if not STA_IF.isconnected():
        #    IP = AIP

        print("AP_IF", AP_IF.active(), AIP, essid, '*' * len(password) )

        if "network" in os.listdir("/"):
            STA_IF.active(True)

            if AP_IF.active():
                Time.sleep(1)

            try:
                STA_IF.disconnect()
            except:
                pass

            essid, password = connect("network")

            if not "IP" in os.listdir("/"):
                print("connect",essid,password)
                try:
                    STA_IF.disconnect()
                    STA_IF.active(False)
                    Time.sleep(.5)
                except:
                    pass
            STA_IF.active(True)
            STA_IF.connect(essid, password)
            IP = isconnected(STA_IF)

            if STA_IF.ifconfig()[0][0] != "0":
                with open("IP", "w") as f:
                    print(IP, file=f)
                    print(IP, Time.localtime())
            print("network", "STA_IF", IP)

            # turn off network cnx debug
            __import__("esp").osdebug(None)

            # FIXME: loss connex renew dhcp



        del connect, isconnected

        network = STA_IF

        print("STA_IF", STA_IF.active(), STA_IF.isconnected(), essid, IP)


    if "/lib" in sys.path:
        sys.path.remove("/lib")

    try:
        import urequests
    except:
        sys.path.append('/rom')
        import urequests

    if "uses" in os.listdir("/"):
        # NEED FIX
        # sys.modules['__main__'] == __import__(__name__)
        # https://github.com/micropython/micropython/issues/4427

        import ujson as json

        sys.path.append("/xpy/esp")
        sys.path.append("/assets")  # android runtime folder

        setattr(builtins, "sys", sys)
        setattr(builtins, "builtins", builtins)

        builtins.os = os

        import xpy.builtins

        del sys.modules["xpy.builtins"]

        del config

        report(free)

        try:
            import asyncio
        except:
            sys.path.append("rom")
            import uasyncio as asyncio

            print("asyncio", "not", "builtins")

        #print("xpy.aio")
        #import xpy.aio

        print("klib")
        export("klib", dlopen("klib"))

        builtins.Pin = klib.Pin

        #export("drv", dlopen("drv"))
        report(free)

        import uio as io
        builtins.io = io
    else:
        print("No framework")
        setattr(builtins, "uses", None)
        setattr(builtins, "use", config)

        #from lib import *
        #from drv import *
        setattr(builtins, "pdb", print)

        globals()["lib"] = __import__(__name__)
        globals()["drv"] = __import__(__name__)

    report(free)


# uasyncio  3632 - 3700
# asyncio  2736
# xpy.aio 1952

#
